<template>
  <div class="login_page">
    <div class="login_box clearfix">
      <div class="center_box">

        <div class="login_form" :class="{login_form: true, rotate: tab == 2}">
          <div :class="{tabs: true, clearfix: true, r180: tabp == 2}">
            <div class="fl tab" @click="changetab(1)"><span :class="{on: tab == 1}">登录</span></div>
            <div class="fl tab" @click="changetab(2)"><span :class="{on: tab == 2}">注册</span></div>
          </div>
          <!--登录-->
          <div class="form_body " v-show="tabp == 1">
            <el-form ref="LoginUserForm" :model="user">
              <!--<input type="text" placeholder="请输入邮箱">-->
              <el-form-item v-if="isMobile" prop="mobile"
                            :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{validator: checkPhone, trigger: 'blur'}]">
                <div>
                  <el-input type="text" placeholder="手机号" v-model="user.mobile"/>
                </div>
              </el-form-item>
              <el-form-item v-else prop="email"
                            :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }]">

                <el-autocomplete
                  style="width: 100%"
                  v-model="user.email"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入邮箱"
                  :trigger-on-focus="false"
                  @select="handleSelect"
                >
                  <template slot-scope="{ item }">
                    <span class="addr">{{ item }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
              <el-form-item prop="password"
                            :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
                <div>
                  <el-input type="password" placeholder="6-20位密码，可用数字/字母/符号组合" v-model="user.password"
                            style="width: 100%" show-password/>
                </div>
              </el-form-item>
              <input type="submit" value="登录" class="btn" :disabled="loginDisabled" :loading="loginDisabled"
                     @click="submitLogin()">
            </el-form>
            <!-- 更多登录方式 -->
            <!--<div class="more-sign" style="margin-top: 5px">
              <h6>社交帐号登录</h6>
              <ul>
                <li><a id="weixin" class="weixin" target="_blank"
                       href="http://localhost:8160/api/ucenter/wx/login"><i class="iconfont icon-weixin"/></a>
                </li>
                <li><a id="qq" class="qq" target="_blank" href="#"><i class="iconfont icon-qq"/></a></li>
              </ul>
            </div>-->
            <div class="b-d-fiex">
              <div>
                <input type="checkbox" class="check">
                <span class="next_auto">下次自动登录</span>
              </div>
              <a href="/reset" class="is_go">忘记密码</a>
            </div>
          </div>
          <!--注册-->
          <div class="form_body r180" v-show="tabp == 2" >
            <el-form ref="regUserForm" :model="params" :rules="registerRules">

              <el-form-item v-if="isMobile" prop="mobile">
                  <el-input type="text" placeholder="手机号" v-model="params.mobile"/>
              </el-form-item>

              <el-form-item v-else prop="email">
                  <el-autocomplete
                    style="width: 100%;"
                    v-model="params.email"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入邮箱"
                    :trigger-on-focus="false"
                    @select="handleRegisterSelect"
                  >
                    <template slot-scope="{ item }">
                      <span class="addr">{{ item }}</span>
                    </template>
                  </el-autocomplete>

              </el-form-item>
              <!--<input type="text" placeholder="请输入邮箱">-->
              <el-form-item prop="code">

                <div class="phone_yzm">
                  <el-input type="text" v-model="params.code" placeholder="请输入邮箱验证码" class="phone"
                         maxlength="6"/>
                  <button  type="button" class="yzm_btn" :class="{'yzm_btn_dis':!sending}" @click="getCodeFun()">
                    {{codeTest}}
                  </button>
                </div>
              </el-form-item>
              <el-form-item prop="password">
                <el-input type="password" placeholder="6-20位密码，可用数字/字母/符号组合" v-model="params.password" show-password/>
              </el-form-item>

              <el-form-item prop="pwd2">
                <el-input type="password" v-model="params.pwd2" placeholder="确认密码" show-password/>
              </el-form-item>

              <div class="mt20 f14">
                <input type="checkbox" id="tonyi" v-model="checked">
                <label for="tonyi">我已经阅读并同意</label><a href="jvascript:void(0)" class="c_blue" @click="xieyi = true">《用户协议》</a>
              </div>
              <input type="button" v-if="regBtnDis" disabled="disabled" value="提交中···" class="btn">
              <input type="button" v-else value="注册"  @click="submitRegister()"  class="btn">
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>
<script>
  import '~/assets/css/sign.css'
  import '~/assets/css/iconfont.css'
  import cookie from 'js-cookie'

  import loginApi from '@/api/login'
  import registerApi from '@/api/register'

  export default {
    layout: 'sign',

    data() {
      let validatePass2=(rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.params.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        tab: this.$route.query.tab || 1,
        tabp: this.$route.query.tab || 1,
        returnUrl:this.$route.query.r || '/',
        user: {
          mobile: '',
          password: '',
          email: '',
          regType: this.isMobile ? 'mobile' : 'email', //验证方式 后端防止篡改

        },
        loginInfo: {},
        isMobile: false, //是否手机注册 否为邮箱
        loginDisabled: false,
        params: {
          mobile: '',
          code: '',
          nickname: '',
          password: '',
          email: '',
          pwd2:'',
          regType: this.isMobile ? 'mobile' : 'email' //验证方式 后端防止篡改
        },
        checked:false,
        sending: true,      //是否发送验证码
        second: 60,        //倒计时间
        codeTest: '获取验证码',
        registerRules: {
          mobile:[{ required: true, message: '请输入手机号码', trigger: 'blur' }]
          ,email:[{ required: true, message: '请输入邮箱', trigger: 'blur' }]
          ,code:[{ required: true, message: '请输入验证码', trigger: 'blur' }]
          ,password:[{ required: true, message: '请输入密码', trigger: 'blur' }]
          ,pwd2:[{ required: true, message: '请确认密码',trigger: 'blur' ,validator: validatePass2}]
        },
        regBtnDis:false

      }
    },

    methods: {
      submitLogin() {
        this.loginDisabled = true
        loginApi.submitLogin(this.user).then(response => {
          if (response) {
            //把token存在cookie中、也可以放在localStorage中
            //we: wisdom education
            console.log(response)

            cookie.set('we_token', response)
            //登录成功根据token获取用户信息
            loginApi.getLoginInfo().then(response => {

              this.loginInfo = response
              //将用户信息记录cookie
              cookie.set('we_ucenter', this.loginInfo);
              // this.$store.dispatch("setUserInfo", this.loginInfo)
              //跳转页面
              window.location.href = this.returnUrl;
            })
          }

        }).catch(() => {
          this.loginDisabled = false
        })

      },

      checkPhone(rule, value, callback) {
        //debugger
        if (!(/^1[34578]\d{9}$/.test(value))) {
          return callback(new Error('手机号码格式不正确'))
        }
        return callback()
      },
      handleSelect(item) {
        if (!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(item))) {
          return new Error('邮箱格式不正确')
        }
        this.user.email = item
      },
      handleRegisterSelect(item) {
        if (!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(item))) {
          return new Error('邮箱格式不正确')
        }
        this.params.email = item
      },
      //输入建议
      querySearch(queryString, cb) {
        const emailsuffix = ["@qq.com", "@163.com", "@gmail.com", "@yahoo.com"]
        let results = [];
        if ((queryString.split('@')).length - 1 === 0) {//判断@符号没出现 就添加邮箱建议
          for (let i = 0; i < emailsuffix.length; i++) {
            results[i] = queryString + emailsuffix[i];
          }
        }
        cb(results);
      },
      changetab(int) {
        this.tab = int;
        let _that = this;
        setTimeout(function () {
          _that.tabp = int
        }, 200)
      },
      getCodeFun() {
        //sending = false
        //his.sending原为true,请求成功，!this.sending == true，主要是防止有人把disabled属性去掉，多次点击；
        if (!this.sending)
          return;

        //debugger
        // prop 换成你想监听的prop字段
        const key = this.isMobile ? 'mobile' : 'email'
        this.$refs.regUserForm.validateField(key, (errMsg) => {
          if (errMsg == '') {
            if (this.isMobile) {
              //获取手机验证码
              registerApi.getMobile(this.params.mobile).then(res => {
                this.sending = false;
                this.timeDown();
              });
            } else {
              //获取邮箱验证码
              registerApi.getEmail(this.params.email).then(res => {
                this.sending = false;
                this.timeDown();
              });
            }

          }
        })
      },
      timeDown() {
        let result = setInterval(() => {
          --this.second;
          this.codeTest = this.second
          if (this.second < 1) {
            clearInterval(result);
            this.sending = true;
            //this.disabled = false;
            this.second = 60;
            this.codeTest = "获取验证码"
          }
        }, 1000);

      },
      submitRegister() {
        if(!this.checked){
          //提示注册成功
          this.$message.warning("请先同意协议")
          return false;
        }
        this.regBtnDis=true
        if(!this.isMobile){
          this.params.nickname= this.params.email.substring(0,this.params.email.indexOf("@"));
          this.params.nickname=this.params.nickname.substring(0,6);
        }else{
          this.params.nickname= this.params.mobile.substring(0,6);
        }
        this.$refs['regUserForm'].validate((valid) => {
          if (valid) {
            registerApi.submitRegister(this.params).then(response => {
              //提示注册成功
              this.$message({
                type: 'success',
                message: "注册成功"
              })
              // this.$router.push({path: '/login?tab=1'})
              this.changetab(1)
            }).catch(()=>{
              this.regBtnDis=false
            })
          }
        })
      },
    }
  }
</script>
<style scoped>
  .login_box {
    height: 600px;
    background: url(./static/login_bg.871a966.jpg) no-repeat 50%;
  }

  .cl:before, .clearfix:before, .container:before {
    content: "";
    display: table;
  }

  .center_box {
    width: 1200px;
    margin: 0 auto;
    position: relative;
  }

  .login_page .login_form {
    width: 380px;
    position: absolute;
    top: 80px;
    right: 0;
    border-radius: 6px;
    transition: all .8s;
    transform: perspective(600px);
  }

  .login_page .tabs {
    height: 60px;
    line-height: 60px;
    background: #fff;
    border-radius: 8px 8px 0 0;
    border-bottom: 1px solid #e6e6e6;
  }

  .login_page .tabs {
    height: 60px;
    line-height: 60px;
    background: #fff;
    border-radius: 8px 8px 0 0;
    border-bottom: 1px solid #e6e6e6;
  }

  .login_page .tabs .tab {
    font-size: 18px;
    width: 50%;
    text-align: center;
    cursor: pointer;
    line-height: 60px;
  }

  .login_page .tabs .on {
    border-bottom: 2px solid #d51423;
    color: #d51423;
  }

  .login_page .tabs span {
    display: inline-block;
    height: 60px;
  }

  .login_page .form_body {
    background: #fff;
    padding: 0 30px 20px;
    border-radius: 0 0 6px 6px;
  }

  /deep/ .el-input,.form_body input[type=submit].btn,.form_body input[type=button] {
    margin-top: 20px;
  }
  /deep/ .el-input .el-input__inner, .login_page .form_body input[type=password], .login_page .form_body input[type=submit], .login_page .form_body input[type=button], .login_page .form_body input[type=text] {
    width: 310px;
    height: 46px;
    padding-left: 10px;
    border-radius: 6px;
    font-size: 14px;
    border-color: #e6e6e6;
  }

  .login_page .form_body .error_msg {
    width: 310px;
    color: #d51423;
    font-size: 12px;
  }

  .login_page .form_body input[type=submit].btn ,input[type=button].btn{
    background: #d51423;
    width: 320px;
    color: #fff;
    border: none;
    outline: none;
    cursor: pointer;
    margin-bottom: 20px;
  }

  /deep/ .el-input__inner, input {
    border: 1px solid #ccc;
    padding: 0;
    border-radius: 0;
    outline: none;
    font-size: 12px;
  }

  /deep/ input::-webkit-input-placeholder {
    color: #818181
  }

  /deep/ .el-form-item {
    margin-bottom: unset;
  }

  .login_page .form_body input[type=submit].btn:disabled, .login_page .form_body input[type=submit].btn:disabled:hover {
    background-color: #e9838b;
    cursor: not-allowed;

  }
  .yzm_btn_dis{
    background-color: #107bc58c;
    cursor: not-allowed;
  }
  .login_page .check {
    width: 14px;
    height: 14px;
    position: relative;
    top: 2px;
  }

  .login_page .form_body .next_auto {
    font-size: 14px;
    color: #333;
  }

  .login_page .form_body .is_go {
    float: right;
    color: #09f;
    height: 18px;
    line-height: 18px;
    font-size: 14px;
    display: inline-block;
    padding: 0 10px;
  }

  .b-d-fiex {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .login_page .phone_yzm {
    position: relative;
  }

  .login_page .yzm_btn {
    width: 100px;
    height: 46px;
    position: absolute;
    left: 215px;
    top: 21px;
    line-height: 48px;
    border-radius: 0 6px 6px 0;
    text-align: center;
    color: #fff;
    cursor: pointer;
    border: none;
  }

  button {
    line-height: 33px;
    padding: 0;
    width: 100px;
    background-color: #107bc5;
    border: 1px solid #0f75bb;
    color: #fff;
    border-radius: 3px;
  }

  .login_page .r180 {
    transform: rotateY(-180deg);
  }

  .login_page .login_form.rotate {
    transform: rotateY(-180deg);
  }

</style>
